package lk.icta.core.web.action;

import lk.icta.common.util.KmlWriter;
import lk.icta.common.web.action.BaseAction;
import lk.icta.core.dto.GeoParcelCodeDetail;
import lk.icta.core.entity.GOInterestInformation;
import lk.icta.core.entity.GeoParcelCode;
import lk.icta.core.entity.Land;
import lk.icta.core.service.GOInterestManagementService;
import lk.icta.core.service.LandManagementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * Created by IntelliJ IDEA.
 * User: Mahesha Kalpanie
 * Date: 8/24/12
 * Time: 12:29 PM
 * To change this template use File | Settings | File Templates.
 */
public class GeoInfoAction extends BaseAction {

    private final LandManagementService landManagementService;
    private final GOInterestManagementService goInterestManagementService;
    private static final Logger logger = LoggerFactory.getLogger(GeoInfoAction.class);

    private long goInterestInformationId;
    private long landId;
    private File kmlFile;
    private Land land;
    private GOInterestInformation goInterestInformation;

    private String kmlString;
    //private String kmlCoordinates;
    private String kmlMiddlePoint;
    private long kmlReferenceNumber;
    private String latLonStr;


    public GeoInfoAction(LandManagementService landManagementService, GOInterestManagementService goInterestManagementService) {
        this.landManagementService = landManagementService;
        this.goInterestManagementService = goInterestManagementService;
    }

    public String loadKMLPage() {
        logger.debug("load kml data ------------------------ Land Id {}", landId);
        try {
            land = landManagementService.getLandById(landId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }

    public String saveGISData() {
        //todo: Handle errors
        try {
            land.setId(landId); //todo: remove this if already set
            logger.debug("save GIS DATA {}");
            landManagementService.updateGEOInfo(land, user);




            //todo: language translation required here
            addActionMessage(getText("geoInfo_saved_success.label"));
        } catch (Exception e) {
            e.printStackTrace();
            addActionMessage(getText("geoInfo_saved_fail.label"));
            return ERROR;
        }

        return SUCCESS;
    }

    public String getKMLData() {
        if (kmlFile == null) {
            addActionError("Please upload valid KML file");
            return SUCCESS;
        }
        logger.debug("getting kml data");
        logger.debug("getting kml data - Land Id {}", landId);
        logger.debug(kmlFile.toString());
        try {
            land = landManagementService.getLandById(landId);

            // kmlString = KmlWriter.getCoordinateValue(kmlFile);
            /* String kmlString = "80.120705,6.7987313,62.2 80.120834,6.7987604,54.2 80.12164,6.799118,39.5 80.12164,6.799129,40.0 80.122185,6.799121,39.0 80.12218,6.7991266,38.2 80.12214,6.7990117,37.7 80.12201,6.7985067,33.7 80.121994,6.7985106,34.0 80.121574,6.7968874,28.2 80.121574,6.7969036,28.1 80.12152,6.7968416,28.2";
            logger.debug(kmlString);
            //TODO : kusal needs to find GIS data using uploaded kml and set below fields
            land.setReferenceNumber(land.getId());
            land.setKmlLandArea(34.4);
            land.setKmlString(kmlString);*/

            //TODO: Write seperate service class for GIS
            KmlWriter kmlWriter = new KmlWriter();
            //get the coordinations
            String kmlCoordinations = kmlWriter.getCoordinateValue(kmlFile).trim();
            //create new kml string
            if (!"".equals(kmlCoordinations) || kmlCoordinations.length() > 0) {
                //logger.debug(kmlCoordinations);
                //setKmlCoordinates(kmlCoordinations.trim());
                kmlWriter.writeKmlFileFromCoordinate(kmlCoordinations);

                logger.debug("KML Ref Number -- {}", kmlWriter.getReferenceNo());

                if (kmlWriter.getReferenceNo() != 0) {

                    //TODO : Find only active lands. Deleted land ref numbers should allow
                    if (landManagementService.getLandByRef(kmlWriter.getReferenceNo()) != null) {
                        logger.debug("Duplicate ref number");
                        addActionError("Duplicate Land Reference Number " + kmlWriter.getReferenceNo()
                                + ". Please upload valid KML file.");
                        return SUCCESS;
                    }
                } else {
                    addActionError("Invalid Land Reference Number!");
                    return SUCCESS;
                }

                //TODO Remove this unwanted code, attributes in action class
                setKmlString(kmlCoordinations.trim());
                setKmlReferenceNumber(kmlWriter.getReferenceNo());
                //setKmlMiddlePoint(kmlWriter.getMiddlePoint(getKmlString()));

                GeoParcelCodeDetail middlePoint = kmlWriter.getMiddlePoint(getKmlString());

                String resultPoint = middlePoint.getLatitude() + "," + middlePoint.getLongitude() + "," +
                        middlePoint.getAltitude();
                setKmlMiddlePoint(resultPoint);

                logger.debug("Middle Point ={}", resultPoint);
                //latlonList=kmlWriter.getOnlyLatLonValueFromSavedFile(kmlCoordinates);
                setLatLonStr(kmlWriter.getOnlyLatLonValue(getKmlString()));

                //set land data

                land.setKmlString(getKmlString());
                land.setKmlMiddlePoint(getKmlMiddlePoint());

                GeoParcelCode geoParcelCode=new GeoParcelCode();
                geoParcelCode.setLatitude(middlePoint.getLongitude());
                geoParcelCode.setLongitude(middlePoint.getLatitude());
                geoParcelCode.setAltitude(middlePoint.getAltitude());



                //logger.debug("Full kml Data {}", getKmlString());
                logger.debug("coordinates {}", getKmlString());
                logger.debug("Ref No {}", getKmlReferenceNumber());
                logger.debug("kmlMiddlePoint {}", getKmlMiddlePoint());
                logger.debug("Lat Lon list {}", getLatLonStr());

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }

    /*public String getKMLData() {
        logger.debug("getting kml data");
        logger.debug("getting kml data - Land Id {}", landId);
        logger.debug(userImage.toString());
        KmlWriter kmlWriter = new KmlWriter();
        //get the coordinations
        String kmlCoordinations = kmlWriter.getCoordinateValue(userImage).trim();
        //create new kml string
        if (kmlCoordinations != null || kmlCoordinations.length() > 0) {
            //logger.debug(kmlCoordinations);
            setKmlCoordinates(kmlCoordinations.trim());
            setKmlString(kmlWriter.writeKmlFileFromCoordinate(getKmlCoordinates()));
            setKmlReferenceNumber("" + kmlWriter.getReferenceNo());
            setKmlMiddlePoint(kmlWriter.getMiddlePoint(getKmlCoordinates()));
            //latlonList=kmlWriter.getOnlyLatLonValueFromSavedFile(kmlCoordinates);
            setLatLonStr(kmlWriter.getOnlyLatLonValue(getKmlCoordinates()));

            logger.debug("Full kml Data {}", getKmlString());
            logger.debug("coordinates {}", getKmlCoordinates());
            logger.debug("Ref No {}", getKmlReferenceNumber());
            logger.debug("kmlMiddlePoint {}", getKmlMiddlePoint());
            logger.debug("Lat Lon list {}", getLatLonStr());

        }


        //kmlString = "80.120705,6.7987313,62.2 80.120834,6.7987604,54.2 80.12164,6.799118,39.5 80.12164,6.799129,40.0 80.122185,6.799121,39.0 80.12218,6.7991266,38.2 80.12214,6.7990117,37.7 80.12201,6.7985067,33.7 80.121994,6.7985106,34.0 80.121574,6.7968874,28.2 80.121574,6.7969036,28.1 80.12152,6.7968416,28.2";

        return SUCCESS;
    }*/

    public String getKMLDataGOInterest() {
        if (kmlFile == null) {
            addActionError("Please upload valid KML file");
            return SUCCESS;
        }
        logger.debug("getting kml data GO ID: {}", goInterestInformation.getId());
        logger.debug(kmlFile.toString());
        try {
            goInterestInformation = goInterestManagementService.getGOInterestInformationById(goInterestInformation.getId(), user);


            KmlWriter kmlWriter = new KmlWriter();
            //get the coordinations
            String kmlCoordinations = kmlWriter.getCoordinateValue(kmlFile).trim();
            //create new kml string
            if (!"".equals(kmlCoordinations) || kmlCoordinations.length() > 0) {
                //logger.debug(kmlCoordinations);
                //setKmlCoordinates(kmlCoordinations.trim());
                kmlWriter.writeKmlFileFromCoordinate(kmlCoordinations);

                logger.debug("KML Ref Number -- {}", kmlWriter.getReferenceNo());

                if (kmlWriter.getReferenceNo() == 0) {
                    addActionError("Invalid Land Reference Number!");
                    return SUCCESS;

                    /*if (goInterestManagementService.getLandByRef(kmlWriter.getReferenceNo()) != null) {
                        logger.debug("Duplicate ref number");
                        addActionError("Duplicate Land Reference Number " + kmlWriter.getReferenceNo()
                                + ". Please upload valid KML file.");
                        return SUCCESS;
                    }*/
                } /*else {

                }*/


                setKmlString(kmlCoordinations.trim());
                setKmlReferenceNumber(kmlWriter.getReferenceNo());

                //setKmlMiddlePoint(kmlWriter.getMiddlePoint(getKmlString()));

                GeoParcelCodeDetail middlePoint = kmlWriter.getMiddlePoint(getKmlString());

                String resultPoint = middlePoint.getLatitude() + "," + middlePoint.getLongitude() + "," +
                        middlePoint.getAltitude();
                setKmlMiddlePoint(resultPoint);


                setLatLonStr(kmlWriter.getOnlyLatLonValue(getKmlString()));

                //set land data
                goInterestInformation.setReferenceNumber("" + getKmlReferenceNumber());
                goInterestInformation.setKmlString(getKmlString());
                goInterestInformation.setKmlMiddlePoint(getKmlMiddlePoint());

                //logger.debug("Full kml Data {}", getKmlString());
                logger.debug("coordinates {}", getKmlString());
                logger.debug("Ref No {}", getKmlReferenceNumber());
                logger.debug("kmlMiddlePoint {}", getKmlMiddlePoint());
                logger.debug("Lat Lon list {}", getLatLonStr());

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }

    public String saveGOInterestGISData() {

        logger.debug("save GOInterest GIS DATA");
        logger.debug("GO ID :{}", goInterestInformation.getId());
        try {
            GOInterestInformation oldGoInterestInformation = goInterestManagementService.getGOInterestInformationById(goInterestInformation.getId(), user);
            oldGoInterestInformation.setKmlLandArea(goInterestInformation.getKmlLandArea());
            oldGoInterestInformation.setKmlString(goInterestInformation.getKmlString());
            oldGoInterestInformation.setKmlMiddlePoint(goInterestInformation.getKmlMiddlePoint());

            goInterestManagementService.updateGOInterestInformation(oldGoInterestInformation, user);
            addActionMessage("Geographic Information Saved Successfully!");

        } catch (Exception e) {
            addActionError("Geographic Information Saved Fail!");

        }

        return SUCCESS;
    }


    public long getLandId() {
        return landId;
    }

    public void setLandId(long landId) {
        this.landId = landId;
    }

    public File getKmlFile() {
        return kmlFile;
    }

    public void setKmlFile(File kmlFile) {
        this.kmlFile = kmlFile;
    }

    public Land getLand() {
        return land;
    }

    public void setLand(Land land) {
        this.land = land;
    }

    public String getKmlString() {
        return kmlString;
    }

    public void setKmlString(String kmlString) {
        this.kmlString = kmlString;
    }

    /*public String getKmlCoordinates() {
        return kmlCoordinates;
    }

    public void setKmlCoordinates(String kmlCoordinates) {
        this.kmlCoordinates = kmlCoordinates;
    }*/

    public String getKmlMiddlePoint() {
        return kmlMiddlePoint;
    }

    public void setKmlMiddlePoint(String kmlMiddlePoint) {
        this.kmlMiddlePoint = kmlMiddlePoint;
    }

    public long getKmlReferenceNumber() {
        return kmlReferenceNumber;
    }

    public void setKmlReferenceNumber(long kmlReferenceNumber) {
        this.kmlReferenceNumber = kmlReferenceNumber;
    }

    //this is used to calculate kml land area
    public String getLatLonStr() {
        return latLonStr;
    }

    public void setLatLonStr(String latLonStr) {
        this.latLonStr = latLonStr;
    }

    public GOInterestInformation getGoInterestInformation() {
        return goInterestInformation;
    }

    public void setGoInterestInformation(GOInterestInformation goInterestInformation) {
        this.goInterestInformation = goInterestInformation;
    }

    public long getGoInterestInformationId() {
        return goInterestInformationId;
    }

    public void setGoInterestInformationId(long goInterestInformationId) {
        this.goInterestInformationId = goInterestInformationId;
    }

}
